package com.example.forum2.Controller;

import com.example.forum2.Service.IArtReplyService;
import com.example.forum2.Service.IArticleService;
import com.example.forum2.Service.impl.IArtReplyImpl;
import com.example.forum2.comment.AppResult;
import com.example.forum2.comment.ResultCode;
import com.example.forum2.config.AppConfig;
import com.example.forum2.dao.ArticleReplyMapper;
import com.example.forum2.model.Article;
import com.example.forum2.model.ArticleReply;
import com.example.forum2.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/reply")
public class ArtReplyController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IArtReplyImpl artReplyImy;
    @Autowired
    private ArticleReplyMapper articleReplyMapper;

    @RequestMapping("/create")
    public AppResult create(HttpServletRequest request,Long articleId,String content){
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(articleId);
        if(article==null||article.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        if(article.getState()==1){
            return AppResult.failed(ResultCode.FAILED);
        }
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        artReplyImy.create(articleReply);
        return AppResult.success();
    }
    @RequestMapping("/getReplies")
 public AppResult<List<ArticleReply>> getReplyByArticledId(Long articledId){
        Article article = articleService.selectById(articledId);
        article.setDeleteState((byte)0);
        if(article==null||article.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        List<ArticleReply> articleReplies = artReplyImy.selectByArticledId(articledId);
        return AppResult.success(articleReplies);
 }
}
